<?php
/**
 * @version		1.0
 * @package		Information Blocs
 * @author		Dragon's Anime - http://dragonsanime.com
 * @copyright	Copyright (c) 2011-2012 Dragon's Anime. All rights reserved.
 * @license		GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
 */

// no direct access
defined('_JEXEC') or die ('Restricted access');

// Load the K2 Plugin API
JLoader::register('K2Plugin', JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'lib'.DS.'k2plugin.php');

/*
 * Setting DA_DEBUG_MODE_ENABLE to true will enable debug output on a
 * FirePHP enabled server to a browser with FireBug installed and active.
 * This is an advanced operation and should only be done by those who understand
 * the risks of displaying large amounts of debug information.
 */
require_once( JPATH_SITE . DS . 'plugins' . DS . 'k2' . DS . 'iblocs' . DS . 'jfirephp.defines.php' ); // Dummy functions for jFirePHP.
define( 'DA_DEBUG_MODE_ENABLE', false );
//define( 'DA_DEBUG_MODE_ENABLE', true ); // Dangerous!  May expose sensitive information!

// Initiate class to hold plugin events
class plgK2Iblocs extends K2Plugin {

	// Some params
	var $pluginName = 'iblocs';
	var $pluginNameHumanReadable = 'Information Blocs K2 Plugin';

	function plgK2Iblocs( & $subject, $params) {
		parent::__construct($subject, $params);
	}

	//function onK2PrepareContent( &$item, &$params, $limitstart) {
	function onK2BeforeDisplayContent( &$item, &$params, $limitstart) {
		if ( DA_DEBUG_MODE_ENABLE ) {
			FB::group('iBlocs K2 Plugin', array( 'Collasped' => true ) );
			FB::info( 'Entering IBlocs::onK2BeforeDisplayContent' );
			FB::log( $item, 'Entire Item' );
		}
		
		$mf = &JFactory::getApplication();
		$plgIn = &JPluginHelper::getPlugin( 'k2', 'iblocs' );
		$plgInParams = new JParameter( $plgIn->params );
		
		if ( is_string( $item->extra_fields ) && ( strlen( $item->extra_fields ) > 0 )  ) {
			$fieldType = true;
			$eFields = $this->_convertJsonToClass( $item->extra_fields );
			if ( DA_DEBUG_MODE_ENABLE ) {
				FB::log( $item->extra_fields, 'JSON Extra Fields' );
				FB::log( $eFields, 'Decoded Extra Fields' );
			}
		} elseif ( is_array( $item->extra_fields ) ) {	
			if ( DA_DEBUG_MODE_ENABLE ) {
				FB::log( $item->extra_fields, 'StdClass Extra Fields' );
			}
			$fieldType = true;
			$eFields = $item->extra_fields;
		} else {
			if ( DA_DEBUG_MODE_ENABLE ) {
				FB::info( 'No Extra Fields Found' );
			}
			$fieldType = false;
		}
		
		$config = array(
			'blocSets'			=> $plgInParams->get('blocSets', null),
			'fieldType'			=> $fieldType,
			'fltLt'				=> $plgInParams->get('fLeft', 'floatLeft'),
			'fltRt'				=> $plgInParams->get('fRight', 'floatRight'),
			'html5'				=> (bool) $plgInParams->get('html5', true),
			'splitDefs'			=> (bool) $plgInParams->get('splitDefs', true),
			'quickBloc'			=> (bool) $plgInParams->get('quickBloc', true)
		);
		
		if ( DA_DEBUG_MODE_ENABLE ) {
			FB::log( $config, 'Plugin Configuration' );
		}
		
		// Check to see if A) there are defined bloc sets or B) quick blocs are enabled.
		if ( ( $config['blocSets'] ) || $config['quickBloc'] ) {
		
			$bloc = '(' . 'ibloc|ib' . ')'; //Look for the code ibloc or ib
			$flt = '(l|r)'; // End the block with a l or r for the float side.
			$set = '(.+)'; // Capture everything to the next space.
			$sp = '(?: )';
			
			$regex = '#(?:\[)'. $bloc . $sp . $set . $sp . $flt .'(?:\])#';
			
			if ( !preg_match_all( $regex, $item->text, $matches, PREG_SET_ORDER ) ) {
				if ( DA_DEBUG_MODE_ENABLE ) {
					FB::info( 'No blocs found, exiting.' );
					FB::groupEnd();
				}
				return; // Nothing to process, so skip it.
			}
		
			if ( ( trim( $config['blocSets'] ) ) ) {
				$blocSets = explode( "\n", $config['blocSets'] );
				// Set definition: setName;header;ids - one per line.
				if ( DA_DEBUG_MODE_ENABLE ) {
					FB::log($blocSets, 'Exploded Bloc Sets' );
				}
			}
		
			$blocs = array();
			
			foreach ( $blocSets as $blocSet ) {
				$t = explode( ';', $blocSet );
				if ( strpos( $t[2], "\r" ) ) {
					$t[2] = str_replace( "\r", '', $t[2] );
				}
				if ( trim( $t[0] ) && trim( $t[1] )
						&& trim( $t[2] ) ) { // Only create a set if all three pieces of information are available.
					
					$blocs[$t[0]] = array(
						'header'	=> $t[1],
						'ids'		=> $t[2]
					);
				}
			}
			
			if ( DA_DEBUG_MODE_ENABLE ) {
				FB::log( $blocs, 'Parsed Bloc Set Definitions' );
			}
			
			if ( count( $matches ) ) {
				if ( DA_DEBUG_MODE_ENABLE ) {
					FB::group('Shortcode Processing Loop', array( 'Collapsed' => true ) );
					FB::log( $matches, 'Matched Shortcodes' );
				}
				
				foreach ( $matches as $m ) {
					if ( DA_DEBUG_MODE_ENABLE ) {
						FB::group('Bloc Match', array( 'Collapsed' => true ) );
						FB::log( $m, 'Matched Shortcode' );
					}
					$output = null;
					
					if ( strpos( $m[2], '::' ) && $config['quickBloc'] ) {
						$output = $this->_getFly( $m[2], $m[3], $config );
					} elseif ( strpos( $m[2], '{{') && !$config['quickBloc'] ) {
						if ( DA_DEBUG_MODE_ENABLE ) {
							FB::info( 'QuickBloc Shortcode - QuickBlocs Disabled' );
						}
						$output = ''; // We'll remove the searched shortcode from the display.
					} else {
						if ( $config['fieldType'] ) { // There are extra fields to read from.
							if ( isset( $blocs[$m[2]] ) ) { // The requested bloc set exists.
								$output = $this->_getBloc( $eFields, $blocs[$m[2]]['ids'], $blocs[$m[2]]['header'], $m[3], $config );
							} else { // The requested bloc set doesn't exist.
								if ( DA_DEBUG_MODE_ENABLE ) {
									FB::log( $m, 'Bloc Set Not Found' );
								}
								$output = ''; // We'll remove the searched shortcode from the display.
							}
						} else { // There are no extra fields to read from.
							if ( DA_DEBUG_MODE_ENABLE ) {
								FB::info( 'No extra fields set - removing shortcode.' );
							}
							$output = ''; // We'll remove the searched shortcode from the display.
						}
					}
					if ( DA_DEBUG_MODE_ENABLE ) {
						FB::log( $output, 'Generated Output' );
						FB::groupEnd();
					}
					$item->text = str_replace( $m[0], $output, $item->text );
				}
				if ( DA_DEBUG_MODE_ENABLE ) {
					FB::groupEnd();
				}
			}
		} else {
			if ( DA_DEBUG_MODE_ENABLE ) {
				FB::log( 'No extra fields, and quickBlocs disabled.' );
				FB::groupEnd();
			}
			return; // There's nothing to process.
		}
		
		if ( DA_DEBUG_MODE_ENABLE ) {
			FB::log( $item, 'Modified Item' );
			FB::groupEnd();
		}
	}
	
	protected function _buildList( $values, $header, $float, $cfg ) {		
		$fTypes = array( 'labels', 'textfield', 'multipleSelect' );
		$float = ( ( $float == 'r' ) ? $cfg['fltRt'] : $cfg['fltLt'] );
		
		if ( $cfg['html5'] ) {
			$dl = '<aside class="ibloc ' . $float . '">' . "\n";
		} else {
			$dl = '<div class="ibloc ' . $float . '">' . "\n";
		}
		
		if ( $header ) {
			$dl .= "\t" . '<h6 class="ibHeader">' . $header . '</h6>' . "\n";
		}
		$dl .= "\t" . '<dl class="ibList">' . "\n";
		
		foreach ( $values as $v ) {
			$dl .= "\t\t" . '<dt class="ibCaption">' . $v['caption'] . '</dt>' . "\n";
			if ( $cfg['splitDefs'] &&
				( in_array( $v['type'], $fTypes ) ) ) {
				$defs = explode( ', ', $v['body'] );
				foreach ( $defs as $dd ) {
					$dl .= "\t\t" . '<dd class="ibBody">' . trim( $dd ) . '</dd>' . "\n";
				}
			} else {
				$dl .= "\t\t" . '<dd class="ibBody">' . trim( $v['body'] ) . '</dd>' . "\n";
			}
		}
		
		$dl .= "\t" . '</dl>' . "\n";
		
		if ( $cfg['html5'] ) {
			$dl .= '</aside>' . "\n";
		} else {
			$dl .= '</div>' . "\n";
		}
		
		$dl .= '<!-- End .ibloc -->';
		
		return $dl;
	}
	
	protected function _convertJsonToClass( $itemExtraFields ){	
		jimport('joomla.filesystem.file');
		$db = &JFactory::getDBO ();
		require_once(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'lib'.DS.'JSON.php');
		$json=new Services_JSON;
		$jsonObjects=$json->decode($itemExtraFields);
		$imgExtensions = array('jpg','jpeg','gif','png');
		$params = & K2HelperUtilities::getParams('com_k2');

		if (count($jsonObjects)<1)
		return NULL;

		foreach ($jsonObjects as $object){
			$extraFieldsIDs[]=$object->id;
		}
		JArrayHelper::toInteger($extraFieldsIDs);
		$condition=@implode(',',$extraFieldsIDs);

		$query="SELECT * FROM #__k2_extra_fields WHERE published=1 AND id IN ({$condition}) ORDER BY ordering ASC";
		$db->setQuery($query);
		$rows = $db->loadObjectList();

		for ($i=0; $i<sizeof($rows); $i++){

			$value='';
			$values = array();
			foreach ($jsonObjects as $object){

				if ($rows[$i]->id==$object->id){

					if ( $rows[$i]->type=='textfield'|| $rows[$i]->type=='textarea' || $rows[$i]->type=='date'){
						$value=$object->value;
						if($rows[$i]->type == 'date') {
							$value = JHTML::_('date', $value, JText::_('K2_DATE_FORMAT_LC'));
						}
						
					}
					else if($rows[$i]->type=='labels'){
						$labels = explode(',', $object->value);
						if(!is_array($labels)){
							$labels = (array)$labels;
						}
						$value='';
						foreach($labels as $label){
							$label = JString::trim($label);
							$label = str_replace('-',' ' ,$label);
							$value.='<a href="'.JRoute::_('index.php?option=com_k2&view=itemlist&task=search&searchword='.urlencode($label)).'">'.$label.'</a> ';
						}


					}

					else if($rows[$i]->type=='select'|| $rows[$i]->type=='radio'){
						foreach ($json->decode($rows[$i]->value) as $option){
							if ($option->value==$object->value)
							$value.=$option->name;
						}
					}

					else if ($rows[$i]->type=='multipleSelect'){
						foreach ($json->decode($rows[$i]->value) as $option){
							if (@in_array($option->value,$object->value))
							$values[]=$option->name;
						}
						$value=@implode(', ',$values);
					}

					else if ($rows[$i]->type=='csv'){
						$array = $object->value;
						if(count($array)){
							$value.='<table cellspacing="0" cellpadding="0" class="csvTable">';
							foreach($array as $key=>$row){
								$value.='<tr>';
								foreach($row as $cell){
									$value.=($key>0)?'<td>'.$cell.'</td>':'<th>'.$cell.'</th>';
								}
								$value.='</tr>';
							}
							$value.='</table>';
						}

					}

					else {
						foreach ($json->decode($rows[$i]->value) as $option){

							switch ($object->value[2]){
								case 'same':
								default:
									$attributes='';
									break;

								case 'new':
									$attributes='target="_blank"';
									break;

								case 'popup':
									$attributes='class="classicPopup" rel="{\'x\':'.$params->get('linkPopupWidth').',\'y\':'.$params->get('linkPopupHeight').'}"';
									break;

								case 'lightbox':
									$filename = @basename($object->value[1]);
									$extension = JFile::getExt($filename);
									if (!empty($extension) && in_array($extension,$imgExtensions)) {
										$attributes='class="modal"';
									}
									else {
										$attributes='class="modal" rel="{handler:\'iframe\',size:{x:'.$params->get('linkPopupWidth').',y:'.$params->get('linkPopupHeight').'}}"';
									}
									break;

							}
							$value = ($object->value[0] && $object->value[1])? '<a href="'.$object->value[1].'" '.$attributes.'>'.$object->value[0].'</a>' : false;
						}
					}

				}

			}
			$rows[$i]->value=$value;
		}
		$K2ItemExtraFieldsInstances[$itemExtraFields] = $rows;
		return $K2ItemExtraFieldsInstances[$itemExtraFields];
	}
	
	protected function _getBloc( $items, $ids, $header = null, $float = 'l', $config ) {
		if ( DA_DEBUG_MODE_ENABLE ) {
			FB::group( 'InfoBloc Shortcode', array( 'Collapsed'=>true ) );
			FB::log( $ids, 'Extra Field IDs' );
			FB::log( $header, 'Bloc Header' );
			FB::log( $float, 'Bloc Float' );
		}
		
		$values = null;
		$values = $this->_readData( $ids, $items, $config );
		
		if ( DA_DEBUG_MODE_ENABLE ) {
			FB::groupEnd();
		}
		return $this->_buildList( $values, $header, $float, $config );
	}
	
	protected function _getFly( $items, $float = 'l', $config ) {
		$items = str_replace( array( '{{', '}}' ), '', $items );
		
		$flyItems = explode( ';', $items ); // [0] Header, [n] Fields
		
		$header = $flyItems[0];
		unset( $flyItems[0] );
		
		$bloc = array();
		foreach ( $flyItems as $item ) {
			$fields = explode( '::', $item );
			$caption = $fields[0];
			unset ( $fields[0] );
			
			$bodyParts = array();
			foreach( $fields as $field ) {
				$bodyParts[] = $field;
			}
			
			$body = implode( ', ', $bodyParts );
			
			$bloc[] = array( 'caption' => $caption, 'body' => $body, 'type' => 'textfield' );
		}
		
		return $this->_buildList( $bloc, $header, $float, $config );
	}
	
	protected function _readData( $ids, $items, $config ) {
		$ids = explode( ',', $ids );
		$v = array();
		
		if ( DA_DEBUG_MODE_ENABLE ) {
			FB::group('Reading Data', array( 'Collapsed' => true ) );
		}
		foreach ( $ids as $id ) {
			if ( DA_DEBUG_MODE_ENABLE ) {
				FB::group( 'Checking ID ' . $id );
			}
			foreach ( $items as $item ) {
				if ( ( $id == $item->id ) && $item->published && strlen( $item->value ) ) {
					switch ( $item->type ) {
						case 'date':
							$item->value = '<date>'.$item->value.'</date>';
							break;
						case 'labels':
							$item->value = str_replace( '</a> ', '</a>, ', $item->value );
							break;
						case 'radio':
						case 'select':
						case 'multipleSelect':
						case 'csv':
						case 'link':
						case 'textarea':
						case 'textfield':
						default:
							break;
					}
					$v[] = array(
						'caption'			=> $item->name,
						'body'				=> $item->value,
						'type'				=> $item->type
					);
					break;
				}
			}
			if ( DA_DEBUG_MODE_ENABLE ) {
				FB::groupEnd();
			}
		}
		if ( DA_DEBUG_MODE_ENABLE ) {
			FB::groupEnd();
		}
		return $v;
	}
} // END CLASS

